package server.service;

import common.Message;
import common.MessageStatus;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Iterator;
import java.util.List;

public class UserThread extends Thread {
    private Socket socket;

    //客户端的没有-----待思考？
    private String userName;
    public  final String storeRootFolder ="A:/IDEAJava/QQServerMySQL/store/";

    public   String personalStoreFolder="";
    public UserThread(String userName, Socket socket,String userAccount) {
        this.userName = userName;
        this.socket = socket;
        createOrCheckStoreFile(userAccount);
    }
    public void createOrCheckStoreFile(String userAccount){
        String store= storeRootFolder +userAccount+"/";
        File file = new File(store);
        if(!file.exists()){
            System.out.println(userAccount+"没有store文件夹："+store+"，因此进行创建");
            if(file.mkdir()){
                System.out.println("成功创建文件夹:"+store);
            }else {
                System.out.println("创建文件夹失败:"+store+"，不能进行文件传递");
                return;
            }
        }
        personalStoreFolder=store;
    }

    @Override
    public void run() {

        while (true) {

            //把本线程输出流放在这里，再打开另一个用户的线程socket的输出流时客户端会出问题
            try {
                System.out.println("等待 " + userName + " 发送消息");

                ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) objIn.readObject();

                if (message.getType() == MessageStatus.GET_ONLINE_FRIEND) {
                    friendList(message);
                } else if (message.getType() == MessageStatus.NORMAL_EXIT) {
                    exists(message);
                    break;
                } else if (message.getType() == MessageStatus.PRIVATE_CHAT) {
                    //好友不在线，会保存到数据库
                    sendMessage(message,message.getGetter(),true,"消息");

                } else if (message.getType() == MessageStatus.GROUP_CHAT) {
                    sendToGroup(message,"消息");

                } else if (message.getType() == MessageStatus.PRIVATE_SEND_FILE) {
                    //好友不在线，会保存到数据库
                   sendMessage(message,message.getGetter(),true,"文件");

                } else if (message.getType() == MessageStatus.GROUP_SEND_FILE) {
                    sendToGroup(message,"文件");
                } else {
                    System.out.println("其他");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void exists(Message message) throws IOException {
        message.setType(MessageStatus.NORMAL_EXIT_SUCCEED);

        ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
        objOut.writeObject(message);
        objOut.flush();

        SocketThreadManager.removeUserThread(userName);

        ServerService.offline(userName);
        System.out.println(userName + " 正常退出");
    }

    public void friendList(Message message) throws IOException {
        System.out.println(userName + " 请求要在线好友列表");
        message.setType(MessageStatus.RETURN_FRIEND_LIST);

        //好像没必要
        message.setGetter(message.getSender());

        String onlineUser = ServerService.getFriendListString(userName);
        message.setContent(onlineUser);

        ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
        objOut.writeObject(message);
        objOut.flush();

        System.out.println("发送在线好友列表给" + userName);
    }

    public void sendToGroup(Message message, String keySayWord) throws IOException {
        System.out.println(message.getSender() + " 请求发送"+keySayWord +"给 " + message.getGetter());

        List<Object> groupNumbersList = ServerService.getGroupNumbersList(message.getGetter());
        Iterator<Object> numbersIterator = groupNumbersList.iterator();
        System.out.println("转发 " + message.getSender() + " 的"+keySayWord +"到 " + message.getGetter());
        System.out.println("总共要转发"+(groupNumbersList.size()-1)+"次");

        while (numbersIterator.hasNext()) {
            String numberName = (String) numbersIterator.next();

            if (numberName.equals(message.getSender())) continue;

            //因为这里的getter是群名，所以要给sendMessage加一个getter参数
            sendMessage(message, numberName, false, "");
        }
    }
    public void sendMessage(Message message,String getter, Boolean needToSaySomething, String keySayWord) throws IOException {
        if(needToSaySomething) {
            System.out.println(message.getSender() + " 请求发送" + keySayWord + "给 " + message.getGetter());
        }

        UserThread getterThread = SocketThreadManager.getUserThread(getter);

        //如果自己发给自己，要不要发？

        //用户不在线，保存到数据库
        if (getterThread == null) {
            saveToDB(message,getter);
            return;
        }

        if(needToSaySomething) {
            System.out.println("转发 " + message.getSender() + " 的" + keySayWord + "给 " + message.getGetter());
        }

        ObjectOutputStream objOut = new ObjectOutputStream(getterThread.getSocket().getOutputStream());
        objOut.writeObject(message);
        objOut.flush();
    }

    public void saveToDB(Message message,String getter) {
        System.out.println(getter+ " 不在线，保存到数据库");
        String storeToFilePath=null;
        if(message.getType()==MessageStatus.GROUP_SEND_FILE||message.getType()==MessageStatus.PRIVATE_SEND_FILE){
            storeToFilePath=personalStoreFolder+message.getFileName();
        }
        ServerService.saveOfflineMessageToDB(message,getter,storeToFilePath);
    }

    public Socket getSocket() {
        return socket;
    }

    public String getUserName() {
        return userName;
    }
}